package at.codebase.db.entities;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Load;

/**
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 */
@Entity
public class EApiAccess {
	@Id
	private Long accessId;
	private boolean active;
	
	private String appName;
	
	@Load
	private Ref<EApiPartner> partner;
	private String comment;
	
	@Index
	private String accessToken;
	
	private EApiAccess(){}
	
	private EApiAccess(boolean active, String appName, Ref<EApiPartner> partner, String comment, String accessToken) {
		this.active = active;
		this.appName = appName;
		this.partner = partner;
		this.comment = comment;
		this.accessToken = accessToken;
	}
	
	public static EApiAccess createApiAccess(String appName, String comment){
		return createApiAccess(appName, null, comment);
	}
	
	public static EApiAccess createApiAccess(String appName, Ref<EApiPartner> partner, String comment){
		String accessToken = "";
		
		try {
			
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());      
			
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES", "BC");
			keyGenerator.init(256);
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] byteKey = secretKey.getEncoded();
			
			for(byte b:byteKey){
				accessToken += String.format("%02X", new Byte(b)); 
			}
		
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			return null;
		}

		if(accessToken != null && !accessToken.trim().equals("")){
			return new EApiAccess(true, appName, partner, comment, accessToken);
		}
		return null;
	}

	public Long getAccessId() {
		return accessId;
	}

	public boolean isActive() {
		return active;
	}
	
	public void setInactive() {
		this.active = false;
	}

	public String getAppName() {
		return appName;
	}

	public Ref<EApiPartner> getPartner() {
		return partner;
	}

	public String getComment() {
		return comment;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setPartner(Ref<EApiPartner> partner) {
		this.partner = partner;
	}


	
}
